package com.ruoyi.web.controller.tool.dataManage;


import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.DbKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.db.DSqlKit;
import com.ruoyi.common.db.DbLink;
import com.ruoyi.common.enums.BusinessType;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/dataManage/sysDatabaseInfo")
public class SysDatabaseInfoController extends BaseController {

    /**
     * 查询多数据源链接信息列表
     */

    @GetMapping("/list")
    public TableDataInfo list(HttpServletRequest request)
    {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageIndex = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        String select="select * ";
        DSqlKit.init(" from sys_database_info where 1=1 ");
        //查询条件
//        数据库服务编码
        String code=request.getParameter("code");
        if(StrKit.notBlank(code)){
            String val = "%" +code+ "%";
            DSqlKit.append(" and (code like ?) ", val);
        }
        String databasetype=request.getParameter("databasetype");
        if(StrKit.notBlank(databasetype)){
            DSqlKit.append(" and dataBaseType = ? ", databasetype);
        }
        String systemname=request.getParameter("systemname");
        if(StrKit.notBlank(systemname)){
            String val = "%" +systemname+ "%";
            DSqlKit.append(" and (systemname like ?) ", val);
        }

        String isemploy=request.getParameter("isemploy");
        if(StrKit.notBlank(isemploy)){
            DSqlKit.append(" and isemploy = ? ", isemploy);
        }
        DSqlKit.append(" order by  sort ");

        Page<Record> page =  Db.paginate(pageIndex, pageSize,select,DSqlKit.getSql(),DSqlKit.getParamList());
        return getDataTable(page);
    }
    /**
     * 获取数据源信息详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        Record data = Db.findById("sys_database_info",id);
        return AjaxResult.success(com.ruoyi.common.db.RecordUtil.RecordToMap(data));
    }
    /**
     * 新增【请填写功能名称】
     */
    @PostMapping("/save")
    public AjaxResult save(@RequestBody SysDatabaseInfo sysDatabaseInfo)
    {
        boolean saveFlag=false;
        if(sysDatabaseInfo.getId() ==null)
        {
            sysDatabaseInfo.setId(UUID.randomUUID().toString());
            Record retrunData= com.ruoyi.common.db.RecordUtil.EntityToRecord(sysDatabaseInfo);
            saveFlag=Db.save("sys_database_info",retrunData);
        }
        else
        {
            Record data=Db.findById("sys_database_info",sysDatabaseInfo.getId());
            Record retrunData= com.ruoyi.common.db.RecordUtil.EntityToRecord(sysDatabaseInfo);
            if(data!=null)
            {
                saveFlag=Db.update("sys_database_info",retrunData);
            }
            else
            {
                saveFlag=Db.save("sys_database_info",retrunData);
            }
        }
        if(saveFlag)
        {
            Record retrunData= com.ruoyi.common.db.RecordUtil.EntityToRecord(sysDatabaseInfo);
            if(sysDatabaseInfo.getIsemploy().equals("Y"))
            {
                DbLink.linkDb(retrunData);
            }
            else
            {
                DbKit.removeConfig(retrunData.get("code").toString());
            }
            return AjaxResult.success("保存成功");
        }
        else
        {
            return AjaxResult.error("保存失败");
        }
    }


    /**
     * 删除【请填写功能名称】
     */
    @Log(title = "【请填写功能名称】", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
//        return toAjax(mpeisCarouselService.deleteMpeisCarouselByIds(ids));
        String newids= ArrayUtils.toString(ids,",").replaceAll("\\{","").replaceAll("}","");
        String val = "'" +newids.replace(",","','")+ "'";
        List<Record> listTmp=Db.find("select * from sys_database_info where id in (?)",val);
        boolean deleteFlag=Db.deleteByIds("sys_database_info","id",newids);
        if(deleteFlag)
        {
            //开始逐行停止删除的数据库链接
            for(Record data:listTmp)
            {
                DbKit.removeConfig(data.get("code").toString());
            }
            return AjaxResult.success("删除成功");
        }
        else
        {
            return AjaxResult.error("删除失败");
        }
    }

    @GetMapping("/getParameterList")
    public TableDataInfo getParameterList(HttpServletRequest request)
    {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageIndex = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        String select="select * ";
        DSqlKit.init(" from sys_parameter where 1=1 ");
        //查询条件
//        数据库服务编码
        String code=request.getParameter("code");
        if(StrKit.notBlank(code)){
            String val = "%" +code+ "%";
            DSqlKit.append(" and (code like ?) ", val);
        }
        String databasetype=request.getParameter("databasetype");
        if(StrKit.notBlank(databasetype)){
            DSqlKit.append(" and dataBaseType = ? ", databasetype);
        }
        String systemname=request.getParameter("systemname");
        if(StrKit.notBlank(systemname)){
            String val = "%" +systemname+ "%";
            DSqlKit.append(" and (systemname like ?) ", val);
        }

        String isemploy=request.getParameter("isemploy");
        if(StrKit.notBlank(isemploy)){
            DSqlKit.append(" and isemploy = ? ", isemploy);
        }
        DSqlKit.append(" order by  sort ");

        Page<Record> page =  Db.paginate(pageIndex, pageSize,select,DSqlKit.getSql(),DSqlKit.getParamList());
        return getDataTable(page);
    }


    @GetMapping(value = "/getDataSource")
    public AjaxResult getDataSource()
    {
        List<Record> list = Db.find("select code,systemName from sys_database_info ");
        return AjaxResult.success(com.ruoyi.common.db.RecordUtil.RecordListToMapList(list));
    }


}
